import 'dart:async';

import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';

import '../utils/Logcat.dart';
import '../utils/PermissionUtils.dart';

class AMapLocation {
  static AMapLocation? _instance;

  AMapLocation._();

  static AMapLocation get instance => _instance ??= AMapLocation._();

  late StreamSubscription<Map<String, Object>> _locationListener;

  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  void locationPlugin(void Function(LatLng) callback) {
    //注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      result.forEach((key, value) {
        Logcat.instance.d("定位信息：key = ${key} ,value = ${value}");
      });
      // 获取经纬度
      Object? latitude = result['latitude'];
      Object? longitude = result['longitude'];
      if (latitude != null && longitude != null) {
        if (latitude is double && longitude is double) {
          LatLng lng = LatLng(latitude, longitude);
          callback(lng);
        }
      }
    });
  }

  //开始定位
  Future<void> startLocation() async {
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    if (await PermissionUtils.instance.requestPermission()) {
      //开始定位之前设置定位参数
      _setLocationOption();
      _locationPlugin.startLocation();
    }
  }

  //停止定位
  void stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  //结束定位
  void cancelLocation() {
    //移除定位监听
    if (null != _locationListener) {
      _locationListener.cancel();
    }
    //销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
  }

  //设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      //是否单次定位
      locationOption.onceLocation = false;

      //是否需要返回逆地理信息
      locationOption.needAddress = true;

      //逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;
      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;
      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      //设置Android端连续定位的定位间隔
      locationOption.locationInterval = 1000 * 10;

      //设置Android端的定位模式<br>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      //设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      //设置iOS端期望的定位精度
      locationOption.desiredAccuracy = DesiredAccuracy.Best;

      //设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      //将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }
}
